"""
@File    :   redis_cache.py
@Time    :   2024/02/06 15:30:23
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   将redis缓存挂载在Fastapi实例上
"""

from fastapi import FastAPI
from redis.asyncio import Redis

from src.config import get_app_settings
from src.enums.redis_db import RedisDbNumEnum

settings = get_app_settings()


class RedisLifeSpan:
    @staticmethod
    async def cache_startup(app: FastAPI):
        """Redis缓存连接池挂载启动事件

        Args:
            app (FastAPI): Fatspi实例
        """

        app.state.redis_cache = Redis(
            host=settings.redis_host,
            password=settings.redis_password,
            port=settings.redis_port,
            db=RedisDbNumEnum.cache_db.value,
            decode_responses=True,
        )

    @staticmethod
    async def cache_shutdown(app: FastAPI):
        """挂载的Redis缓存连接池关闭事件

        Args:
            app (FastAPI): Fatspi实例
        """
        await app.state.redis_cache.close()

    @staticmethod
    async def token_startup(app: FastAPI):
        """Token存储连接池挂载启动事件

        Args:
            app (FastAPI): Fatspi实例
        """
        app.state.redis_token = Redis(
            host=settings.redis_host,
            password=settings.redis_password,
            port=settings.redis_port,
            db=RedisDbNumEnum.token_db.value,
            decode_responses=True,
        )

    @staticmethod
    async def token_shutdown(app: FastAPI):
        """挂载的Token存储连接池关闭事件

        Args:
            app (FastAPI): Fatspi实例
        """
        await app.state.redis_token.close()
